import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:payment/model/PayAndBal.dart';
import 'package:payment/util/DBHelper.dart';

class FormPage extends StatefulWidget {
  final Function() getPayAndBal;
  final num total;
  FormPage({Key? key, required this.getPayAndBal, required this.total})
      : super(key: key);

  @override
  _FormPageState createState() => _FormPageState();
}

class _FormPageState extends State<FormPage> {
  final formKey = new GlobalKey<FormState>();
  final DBHelper dbHelper = new DBHelper();
  final dateFormat = DateFormat('yyyy年MM月dd日');
  final timeFormat = DateFormat('hh:mm:ss');

  String consumptionObject = "";
  String classification = "";

  double consumptionNum = 0;
  int card = 0000;
  double total = 0;
  bool isPay = true;
  String imageStr = "collection";
  String updateTime = '';

  DateTime _date = DateTime.now();
  TimeOfDay _time = TimeOfDay.now();



  List<TextInputFormatter> cardInputFormatters = [
    new LengthLimitingTextInputFormatter(4),
    FilteringTextInputFormatter.allow(RegExp(r'\d+'))
  ];
  List<TextInputFormatter> consumptionNumInputFormatters = [
    FilteringTextInputFormatter.allow(RegExp(r'(^\d*\.?\d{0,2})'))
  ];

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: const Text('添加记录'),
      ),
      body: SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Form(
          key: formKey,
          autovalidateMode: AutovalidateMode.always,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 10),
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.symmetric(vertical: 10),
                  child: Row(
                    children: [
                      Text(
                        "当前余额:" + widget.total.toString(),
                        style: TextStyle(
                            fontSize: 18, fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                ),
                _buildTextFormField("消费对象",
                    (value) => this.consumptionObject = value, nullValidator),
                _buildTextFormField("分类",
                    (value) => this.classification = value, nullValidator),
                _buildTextFormField("卡后四位", (value) {
                  value != '' ? this.card = int.parse(value) : null;
                }, nullValidator, inputFormatters: cardInputFormatters),
                _buildTextFormField(
                    "支出或者收入金额",
                    (value) => {
                          value != ''
                              ? this.consumptionNum = double.parse(value)
                              : null
                        },
                    nullValidator,
                    inputFormatters: consumptionNumInputFormatters),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(dateFormat.format(_date).toString()),
                    _buildPicker("日期选择", _showDatePicker),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(getLocalizations().formatTimeOfDay(_time,alwaysUse24HourFormat: true)),
                    _buildPicker("时间选择", _showTimePicker),
                  ],
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text("模式选择:"),
                    _consumptionRadio(true),
                    Text("支出"),
                    _consumptionRadio(false),
                    Text("收入"),
                  ],
                ),
                _buildWrap(),
                Row(children: [
                  Expanded(
                    child: ElevatedButton(
                      onPressed: _submit,
                      child: Text("确定"),
                    ),
                  ),
                ])
              ],
            ),
          ),
        ),
      ),
    );
  }

  // Row isPayOrBalRow(){
  //   if(this.isPay){
  //     this.imageStr="collection";
  //     return _buildPay();
  //   }else{
  //     this.imageStr="wechatPay";
  //     return _buildBal();
  //   }
  // }
  Widget _buildSelect(String label) {
    return Row(
      children: [
        _imageRadio(label),
        _buildCircleAvatar(label),
      ],
    );
  }

  Future<Null> _selectDate(BuildContext context) async {
    final DateTime? _picked = await showDatePicker(
        context: context,
        initialDate: _date,
        firstDate: new DateTime(1990),
        lastDate: new DateTime(2090));
    if (_picked != null) {
      setState(() {
        _date = _picked;
      });
    }
  }

  Future<Null> _selectTime(BuildContext context) async {
    final TimeOfDay? _picked = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );
    if (_picked != null) {
      setState(() {
        _time = _picked;
      });
    }
  }

  void _showDatePicker() {
    _selectDate(context);
  }

  void _showTimePicker() {
    _selectTime(context);
  }

  Widget _buildPicker(String label, VoidCallback voidCallback) {
    return Center(
      child: OutlinedButton(
        onPressed: voidCallback,
        child: Text(label),
      ),
    );
  }

  Wrap _buildWrap() {
    return Wrap(
      crossAxisAlignment: WrapCrossAlignment.center,
      alignment: WrapAlignment.start,
      children: [
        Text("图片选择:"),
        _buildSelect("collection"),
        _buildSelect("circlePoint"),
        _buildSelect("rollOut"),
        _buildSelect("wechatPay"),
        _buildSelect("aliPay"),
      ],
    );
  }
  MaterialLocalizations getLocalizations(){
    return MaterialLocalizations.of(context);
  }
  void _submit() {

    if (this.formKey.currentState!.validate()) {
      formKey.currentState!.save();
    } else {
      return null;
    }
    print(this.classification);
    this.updateTime=dateFormat.format(_date).toString()+' '+getLocalizations().formatTimeOfDay(_time,alwaysUse24HourFormat: true);
    var payAndBal = PayAndBal(
        0,
        this.consumptionObject,
        this.classification,
        this.card,
        this.isPay
            ? widget.total - this.consumptionNum
            : widget.total + this.consumptionNum,
        this.isPay ? -this.consumptionNum : this.consumptionNum,
        this.isPay,
        this.imageStr,
        this.updateTime);
    dbHelper.insertPayAndBal(payAndBal);
    widget.getPayAndBal();
    _showSnackBar("添加成功");
  }

  _showSnackBar(String label) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(label)));
  }

  _buildCircleAvatar(String imageStr) {
    return Container(
      child: Image.asset(
        'assets/' + imageStr + '.png',
        height: 30,
        width: 30,
      ),
    );
  }

  String? nullValidator(String? value) {
    return (value != null && value.length == 0) ? '不能为空' : null;
  }

  String? consumptionNumValidator(String? value) {
    String pattern = r'(^d{4,}$)';
    RegExp regex = new RegExp(pattern);
    if (value != null && value.length == 0) return '不能为空';
    if (value!.length != 4) {
      return "长度不为4";
    }
    if (!regex.hasMatch(value)) {
      return "不为数字";
    }
    return null;
  }

  Padding _buildTextFormField(String label, onSaved, validator,
      {List<TextInputFormatter>? inputFormatters}) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 3),
      child: TextFormField(
          inputFormatters: inputFormatters,
          decoration: InputDecoration(
              border: OutlineInputBorder(), labelText: label, isDense: true),
          onSaved: onSaved,
          validator: validator),
    );
  }

  Radio _consumptionRadio(dynamic index) {
    return Radio(
      value: index,
      groupValue: isPay,
      onChanged: (value) {
        setState(() {
          isPay = value;
        });
      },
    );
  }

  Radio _imageRadio(dynamic index) {
    return Radio(
      value: index,
      groupValue: imageStr,
      onChanged: (value) {
        setState(() {
          imageStr = value;
        });
      },
    );
  }
}
